<?php
/*
*All rights reserved: Json.
*Links:http://www.liyaoquan.cn.
*Links:http://imarkchina.cn.
*Links:http://www.imarkchina.cn.
*/

/**
* 调用控制器方法 Action('user/editor', $user);
* @param 控制器名/方法名
* @param 可传入多个参数
*/
function A() {
	$args = func_get_args();
	$paths = explode('/', $args[0]);
	$className = ucfirst($paths[0]).'Action';
	$action = isset($paths[1]) ? $paths[1] : '';
	$Control = new $className();
	if (!method_exists($Control, $action)) {
		Debug::add(__METHOD__.' [当有模块中找方法不存在: '.$className.'::'.$action.']');
		include_once JSON_PATH.'/Common/404.php';
		Debug::add(__METHOD__.' [自动调用: '.JSON_PATH.'/Common/404.php]');
	}
	if (isset($args[1])) {
		array_shift($args);
		call_user_func_array(array($Control, $action), $args);
	} else {
		$Control->$action();
	}
}

/**
* 获取和设置配置参数 支持批量定义
* @param string|array $name 配置变量
* @param mixed $value 配置值
* @param mixed $default 默认值
* @return mixed
*/
function C($name=null, $value=null,$default=null) {
	static $_config = array();
	// 无参数时获取所有
	if (empty($name)) {
		return $_config;
	}
	// 优先执行设置获取或赋值
	if (is_string($name)) {
		if (!strpos($name, '.')) {
			$name = strtoupper($name);
			if (is_null($value))
				return isset($_config[$name]) ? $_config[$name] : $default;
			$_config[$name] = $value;
			return null;
		}
		// 二维数组设置和获取支持
		$name = explode('.', $name);
		$name[0]   =  strtoupper($name[0]);
		if (is_null($value))
			return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : $default;
		$_config[$name[0]][$name[1]] = $value;
		return null;
	}
	// 批量设置
	if (is_array($name)){
		$_config = array_merge($_config, array_change_key_case($name,CASE_UPPER));
		return null;
	}
	return null; // 避免非法参数
}


/**
* 获取模型对象
* @param string 模型名
* @return object
*/
function M($modelName = '') {
	$className = ucfirst($modelName).'Model';
	return J::loadClass($className);
}

/**
* 获取URL地址
* @param string $params [U('index/add')]
* [code]
* 当前控制器使用
* U('add')
* 调用Public控制器
* U('public/add')
* 调用板块控制器
* U('root/public/add')
* [/code]
* @param [type] $array  [需要传入的值 array('id'=>1, 'cid'=>2)]
*/
function U($params = null, $array = null, $fix = null) {
	$url = DOMAIN.ROOT_URL;
	if (is_null($params)) return $url;
	$url .= '/';
	$der = C('URLSPACE');
	$mod = strtolower(MODELSNAME);
	$cont = strtolower(CONTROLLERNAME);
	$acti = strtolower(ACTIONNAME);
	if (stristr($params, '/')) {
		$params = explode('/', $params);
	}
	switch (count($params)) {
		case 3:
			$models = $params[0];
			array_shift($params);
			$controller = $params[0];
			array_shift($params);
			$action = $params[0];
			array_shift($params);
			break;
		case 2:
			$models = $mod;
			$controller = $params[0];
			array_shift($params);
			$action = $params[0];
			array_shift($params);
			break;
		case 1:
			$models = $mod;
			$controller = $cont;
			$action = $params;
			break;
		default:
			return null;
	}
	if (!C('URLREWRITE')) {
		$phpSelf = basename($_SERVER['SCRIPT_FILENAME']);
		if ($phpSelf != 'index.php') $url .= $phpSelf;
		$url .= '?m='.$models.'&c='.$controller.'&a='.$action;
		if (is_array($array)) {
			$url .= '&'.http_build_query($array);
		}
		$Gurl = $url;
	} else {
		$res = '';
		if (!C('URLROUTE') || is_null($array)) {
			$url .= $models.$der.$controller.$der.$action;
		}
		if (is_array($array)) {
			foreach ($array as $r => $v) {
				$res .= $der.$r.$der.$v;
			}
		}
		if (C('URLROUTE')) {
			$res = substr($res,1);
			if (is_string($array)) {
				$res .= $array;
			}
		}
		$Gurl = $url.$res;
	}
	if (is_null($fix)) {
		$Gurl .= C('URLFIX');
	}
	return $Gurl;
}

/**
* 打印结果
* 可接收多个不同类型的参数
* @return string
*/
function P() {
	$args = func_get_args();
	if(count($args)<1){
		Debug::add("<font color='red'>必须为p()函数提供参数!");
		return;
	}
	echo '<div style="width:100%;text-align:left"><pre>';
	foreach ($args as $arg) {
		if (is_array($arg)) {
			print_r($arg);
			echo '<br />';
		} else if (is_string($arg)) {
			echo $arg.'<br>';
		} else {
			var_dump($arg);
			echo '<br />';
		}
	}
	echo '</pre></div>';
}

/**
* 判断请求是否为AJAX
* @return bool
*/
function isAjax() {
	if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
		if ('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']))
			return true;
	}
	if (!empty($_GET['ajax'])) return true;
	return false;
}

/**
* 页面跳转
* @param string URL地址
* @param boolean 是否跳出iframe
*/
function Jump($url, $isTop = false) {
	if ($isTop) {
		exit('<script type="text/javascript">window.top.location.href=\''.$url.'\'</script>');
	}
	if (isAjax()) {
		exit('<script type="text/javascript">window.location.href=\''.$url.'\'</script>');
	}
	if (!headers_sent()) {
		header('Location:'.$url);
	} else {
		echo '<meta http-equiv=\'Refresh\' content=\'0;URL='.$url.'\'>';
	}
	exit();
}

/**
* 获取客端IP
* @return string
*/
function GCIP() {
	if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		$realIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
		$realIp = $_SERVER['HTTP_CLIENT_IP'];
	} else {
		$realIp = $_SERVER['REMOTE_ADDR'];
	}
	return preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $realIp) ? $realIp : '127.0.0.1';
}

/**
* 发送header头
* @param string 类型 httpHeader('404');
* @param string 值 httpHeader('charset', 'utf-8');
*/
function httpHeader($type, $value = '') {
	switch ($type) {
		case '403':
		header('HTTP/1.1 403 Forbidden');
		break; //禁止访问
		case '404':
			header('HTTP/1.1 404 Not Found');
			break; //页面不存在
			case '500':
			header('HTTP/1.1 500 Internal Server Error');
			break; //服务器错误
			case 'charset':
			header('Content-type:text/html; charset='.$value);
			break; //设置编码
		case 'download': //下载 eg: httpHeader('download', 'game.zip');
			header('Content-Type: application/octet-stream');
			header('Content-Disposition: attachment; filename="'.$value.'"');
			header('Content-Transfer-Encoding: binary');
			break;
		case 'cache': //缓存页面(单位:小时) eg: httpHeader('cache', 24);
			$value = intval($value) * 3600;
			header('Cache-Control:max-age='.$value.', must-revalidate');
			header('Last-Modified:'.gmdate('D, d M Y H:i:s').'GMT');
			header('Expires:'.gmdate('D, d M Y H:i:s', time() + $value).'GMT');
			break;
		case 'no-cache': //页面禁止缓存
			header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
			header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
			header('Pragma: no-cache');
			break;
		default:
			header($type);
	}
}

/**
* 写入日志
* @param  [type] $message  [需要写入的信息]
* @param  string $filename [文件名]
* @return [type]           [description]
*/
function RLOG($message, $filename = '') {
	J::makeDir(LOG);
	$log = 'time:['.date('Y-m-d H:i:s', time()).']';
	$log .= ' log:['.$message.'] IP:['.GCIP().']'."\r\n";
	if (!$filename) $filename = date('Y-m-d');
	if (!@error_log($log, 3, LOG.$filename.'.log')) {
		throw new Exception(__METHOD__.' [日志写入失败，请检查'.LOG.' log: '.$message.']');
	}
}

/**
* 获取数据库对象
* @param string 表名
* @return object
*/
function D($table = '') {
	$driver = 'Db'.(C('DB_MEMCACHE') ? 'Memcache' : C('DB_DRIVER'));
	$eval = '$Db = '.$driver.'::getInstance();'; //兼容PHP5.2语法
	eval($eval);
	$Db->setTable($table);
	return $Db;
}

/**
* 设置、获取、删除SESSION
* @param string
* @param mixed
* @return mixed
*/
function session($name, $value = '') {
	if (!session_id()) session_start();
	$prefix = 'Json';
	$sessionId = $prefix ? md5($prefix).'_'.$name : $name;
	if (is_null($value)) {
		if (isset($_SESSION[$sessionId])) unset($_SESSION[$sessionId]);
	} else {
		if ($value === '') {
			if (isset($_SESSION[$sessionId])) return $_SESSION[$sessionId];
		} else {
			$_SESSION[$sessionId] = $value;
			return $_SESSION[$sessionId];
		}
	}
}

/**
 * 清除所有Sesssion
 * @return [type] [description]
 */
function clearSession(){
	session_start();
	session_unset();
	session_destroy();
}

/**
* 设置/获取COOKIE
* @param string
* @param mixed
* @return mixed
*/
function cookie($name, $value = '') {
	if (is_null($value)) {
		if (isset($_COOKIE[$name])) {
			setcookie($name, null, TIME - 1, '/', '', C('COOKIESECURE'));
			unset($_COOKIE[$name]);
		}
	} else {
		if ($value == '') {
			if (isset($_COOKIE[$name])) {
				return unserialize(html_entity_decode($_COOKIE[$name]));
			}
		} else {
			$value = serialize($value);
			$expire = TIME + (3600 * C('COOKIETIME'));
			setcookie($name, $value, $expire, '/', '', C('COOKIESECURE'));
			$_COOKIE[$name] = $value;
			return unserialize($value);
		}
	}
}

/**
* 获取输入参数 支持过滤和默认值
* 使用方法:
* <code>
* G('id',0); 获取id参数 自动判断get或者post
* G('post.name','','htmlspecialchars'); 获取$_POST['name']
* G('get.'); 获取$_GET
* </code>
* @param string $name 变量的名称 支持指定类型
* @param mixed $default 不存在的时候默认值
* @param mixed $filter 参数过滤方法
* @param mixed $datas 要获取的额外数据源
* @return mixed
*/
function G($name,$default='',$filter=null,$datas=null) {
	static $_PUT    =   null;
	if(strpos($name,'/')){ // 指定修饰符
		list($name,$type)   =   explode('/',$name,2);
	}
	if(strpos($name,'.')) { // 指定参数来源
		list($method,$name) =   explode('.',$name,2);
	}else{ // 默认为自动判断
		$method =   'param';
	}
	switch(strtolower($method)) {
		case 'get'     :
		$input =& $_GET;
		break;
		case 'post'    :
		$input =& $_POST;
		break;
		case 'put'     :
		if(is_null($_PUT)){
			parse_str(file_get_contents('php://input'), $_PUT);
		}
		$input  =   $_PUT;
		break;
		case 'param'   :
		switch($_SERVER['REQUEST_METHOD']) {
			case 'POST':
			$input  =  $_POST;
			break;
			case 'PUT':
			if(is_null($_PUT)){
				parse_str(file_get_contents('php://input'), $_PUT);
			}
			$input  =   $_PUT;
			break;
			default:
			$input  =  $_GET;
		}
		break;
		case 'path'    :
		$input  =   array();
		if(!empty($_SERVER['PATH_INFO'])){
			$depr   =   C('URLSPACE');
			$input  =   explode($depr,trim($_SERVER['PATH_INFO'],$depr));
		}
		break;
		case 'request' :
		$input =& $_REQUEST;
		break;
		case 'session' :
		$input =& $_SESSION;
		break;
		case 'cookie'  :
		$input =& $_COOKIE;
		break;
		case 'server'  :
		$input =& $_SERVER;
		break;
		case 'globals' :
		$input =& $GLOBALS;
		break;
		case 'data'    :
		$input =& $datas;
		break;
		default:
		return null;
	}
	if(''==$name) { // 获取全部变量
		$data       =   $input;
		$filters    =   isset($filter) ? $filter : 'htmlspecialchars';
		if($filters) {
			if(is_string($filters)){
				$filters    =   explode(',',$filters);
			}
			foreach($filters as $filter){
				$data   =   array_map_recursive($filter,$data); // 参数过滤
			}
		}
	}elseif(isset($input[$name])) { // 取值操作
		$data       =   $input[$name];
		$filters    =   isset($filter)?$filter:'htmlspecialchars';
		if($filters) {
			if(is_string($filters)){
				if(0 === strpos($filters,'/')){
					if(1 !== preg_match($filters,(string)$data)){
					// 支持正则验证
						return   isset($default) ? $default : null;
					}
				}else{
					$filters    =   explode(',',$filters);
				}
			}elseif(is_int($filters)){
				$filters    =   array($filters);
			}
			if(is_array($filters)){
				foreach($filters as $filter){
					if(function_exists($filter)) {
						$data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data); // 参数过滤
					}else{
						$data   =   filter_var($data,is_int($filter) ? $filter : filter_id($filter));
						if(false === $data) {
							return   isset($default) ? $default : null;
						}
					}
				}
			}
		}
		if(!empty($type)){
			switch(strtolower($type)){
				case 'a':   // 数组
				$data   =   (array)$data;
				break;
				case 'd':   // 数字
				$data   =   (int)$data;
				break;
				case 'f':   // 浮点
				$data   =   (float)$data;
				break;
				case 'b':   // 布尔
				$data   =   (boolean)$data;
				break;
				case 's':   // 字符串
				default:
				$data   =   (string)$data;
			}
		}
	}else{ // 变量默认值
		$data       =    isset($default)?$default:null;
	}
	is_array($data) && array_walk_recursive($data,'filter');
	return $data;
}

function array_map_recursive($filter, $data) {
	$result = array();
	foreach ($data as $key => $val) {
		$result[$key] = is_array($val) ? array_map_recursive($filter, $val) : call_user_func($filter, $val);
	}
	return $result;
}

function filter(&$value){
// TODO 其他安全过滤
// 过滤查询特殊字符
	if(preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOTIN|NOT IN|IN)$/i',$value)){
		$value .= ' ';
	}
}

/**
* [过滤函数]
* @param  [type] $str [字符串]
* @return [type]      [description]
*/
function rePlace($str){
	$str = str_replace("\r","",$str);//过滤换行
	$str = str_replace("\n","",$str);//过滤换行
	$str = str_replace("\t","",$str);//过滤换行
	$str = str_replace("\r\n","",$str);//过滤换行
	$str = preg_replace("/\s+/", " ", $str);//过滤多余回车
	$str = preg_replace("/<[ ]+/si","<",$str); //过滤<__("<"号后面带空格)
	$str = preg_replace("/<\!--.*?-->/si","",$str); //过滤html注释
	$str = preg_replace("/<(\!.*?)>/si","",$str); //过滤DOCTYPE
	$str = preg_replace("/<(\/?html.*?)>/si","",$str); //过滤html标签
	$str = preg_replace("/<(\/?head.*?)>/si","",$str); //过滤head标签
	$str = preg_replace("/<(\/?meta.*?)>/si","",$str); //过滤meta标签
	$str = preg_replace("/<(\/?body.*?)>/si","",$str); //过滤body标签
	$str = preg_replace("/<(\/?link.*?)>/si","",$str); //过滤link标签
	$str = preg_replace("/<(\/?form.*?)>/si","",$str); //过滤form标签
	$str = preg_replace("/cookie/si","COOKIE",$str); //过滤COOKIE标签
	$str = preg_replace("/<(applet.*?)>(.*?)<(\/applet.*?)>/si","",$str); //过滤applet标签
	$str = preg_replace("/<(\/?applet.*?)>/si","",$str); //过滤applet标签
	$str = preg_replace("/<(style.*?)>(.*?)<(\/style.*?)>/si","",$str); //过滤style标签
	$str = preg_replace("/<(\/?style.*?)>/si","",$str); //过滤style标签
	$str = preg_replace("/<(title.*?)>(.*?)<(\/title.*?)>/si","",$str); //过滤title标签
	$str = preg_replace("/<(\/?title.*?)>/si","",$str); //过滤title标签
	$str = preg_replace("/<(object.*?)>(.*?)<(\/object.*?)>/si","",$str); //过滤object标签
	$str = preg_replace("/<(\/?objec.*?)>/si","",$str); //过滤object标签
	$str = preg_replace("/<(noframes.*?)>(.*?)<(\/noframes.*?)>/si","",$str); //过滤noframes标签
	$str = preg_replace("/<(\/?noframes.*?)>/si","",$str); //过滤noframes标签
	$str = preg_replace("/<(i?frame.*?)>(.*?)<(\/i?frame.*?)>/si","",$str); //过滤frame标签
	$str = preg_replace("/<(\/?i?frame.*?)>/si","",$str); //过滤frame标签
	$str = preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si","",$str); //过滤script标签
	$str = preg_replace("/<(\/?script.*?)>/si","",$str); //过滤script标签
	$str = preg_replace("/javascript/si","Javascript",$str); //过滤script标签
	$str = preg_replace("/vbscript/si","Vbscript",$str); //过滤script标签
	$str = preg_replace("/on([a-z]+)\s*=/si","On\\1=",$str); //过滤script标签
	$str = preg_replace("/&#/si","&＃",$str); //过滤script标签，如javAsCript:alert();
	return $str;
}

/**
* 取目录中的文件同时排除(.&..)
* @param [type] $directory [路径]
*/
function GetFileList($directory) {
	$files = array();
	if(is_dir($directory)) {
		if($dh = opendir($directory)) {
			while(($file = readdir($dh)) !== false) {
				if($file != '.' && $file != '..') {
					$files[] = $file;
				}
			}
			closedir($dh);
		}
	}
	return $files;
}

/**
* 截取函数
* @param [type] $string   [字符串]
* @param [type] $length   [长度]
* @param string $encoding [默认utf8编码]
*/
function Getstr($string, $length, $encoding = 'utf-8') {
	$string = trim(rePlace($string));
	if ($length && strlen($string) > $length) {
		//截断字符
		$wordscut = '';
		if (strtolower($encoding) == 'utf-8') {
			//utf8编码
			$n = 0;
			$tn = 0;
			$noc = 0;
			while ($n < strlen($string)) {
				$t = ord($string[$n]);
				if ($t == 30 || $t == 100 || (32 <= $t && $t <= 126)) {
					$tn = 1;
					$n++;
					$noc++;
				} elseif (194 <= $t && $t <= 223) {
					$tn = 2;
					$n+= 2;
					$noc+= 2;
				} elseif (224 <= $t && $t < 239) {
					$tn = 3;
					$n+= 3;
					$noc+= 2;
				} elseif (240 <= $t && $t <= 247) {
					$tn = 4;
					$n+= 4;
					$noc+= 2;
				} elseif (248 <= $t && $t <= 251) {
					$tn = 5;
					$n+= 5;
					$noc+= 2;
				} elseif ($t == 252 || $t == 253) {
					$tn = 6;
					$n+= 6;
					$noc+= 2;
				} else {
					$n++;
				}
				if ($noc >= $length) {
					break;
				}
			}
			if ($noc > $length) {
				$n-= $tn;
			}
			$wordscut = substr($string, 0, $n);
		} else {
			for ($i = 0; $i < $length - 1; $i++) {
				if (ord($string[$i]) > 127) {
					$wordscut.= $string[$i] . $string[$i + 1];
					$i++;
				} else {
					$wordscut.= $string[$i];
				}
			}
		}
		$string = $wordscut;
	}
	return strip_tags(trim($string));
}

/**
*转换时间戳
* @param [type] $time [时间戳]
*/
function formDate($time){
	$t=time()-$time;
	$f=array(
		'31536000'=>'年',
		'2592000'=>'个月',
		'604800'=>'星期',
		'86400'=>'天',
		'3600'=>'小时',
		'60'=>'分钟',
		'1'=>'秒'
		);
	foreach ($f as $k=>$v) {
		if (0 !=$c=floor($t/(int)$k)) {
			return $c.$v.'前';
		}
	}
}

/**
* 生成随机数
* @param integer $length [长度]
* @param integer $type   [description]
*/
function randCode($length = 5, $type = 0) {
	$arr = array(
		1 => "0123456789",
		2 => "abcdefghijklmnopqrstuvwxyz",
		3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
		4 => "~@#$%^&*(){}[]|"
		);
	if ($type == 0) {
		array_pop($arr);
		$string = implode("", $arr);
	} elseif ($type == "-1") {
		$string = implode("", $arr);
	} else {
		$string = $arr[$type];
	}
	$count = strlen($string) - 1;
	$code = '';
	for ($i = 0; $i < $length; $i++) {
		$code .= $string[rand(0, $count)];
	}
	return $code;
}

/**
* 获取系统信息
*
* @return array
*/
function getSystemInfo() {
	$systemInfo = array();
	// 系统
	if($sysInfo['win_n'] != '') {
		$systemInfo['os'] = $sysInfo['win_n'];
	}else{
		$systemInfo['os'] = @php_uname();
	}
	// PHP版本
	$systemInfo['phpversion'] = PHP_VERSION;
	// ZEND版本
	$systemInfo['zendversion'] = zend_version();
	// GD相关
	if (function_exists('gd_info')) {
		$gdInfo = gd_info();
		$systemInfo['gdsupport'] = true;
		$systemInfo['gdversion'] = $gdInfo['GD Version'];
	} else {
		$systemInfo['gdsupport'] = false;
		$systemInfo['gdversion'] = '';
	}
	// 安全模式
	$systemInfo['safemode'] = ini_get('safe_mode');
	// 注册全局变量
	$systemInfo['registerglobals'] = ini_get('register_globals');
	// 开启魔术引用
	$systemInfo['magicquotes'] = (function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc());
	// 最大上传文件大小
	$systemInfo['maxuploadfile'] = ini_get('upload_max_filesize');
	// 脚本运行占用最大内存
	$systemInfo['memorylimit'] = get_cfg_var("memory_limit") ? get_cfg_var("memory_limit") : '-';
	//系统版本
	$systemInfo['osrun'] = php_uname();
	//php运行方式
	$systemInfo['phprun'] =  php_sapi_name();
	// Apache版本
	$systemInfo['apacheversion'] = $_SERVER['SERVER_SOFTWARE'];
	//服务器IP
	$systemInfo['hostip'] =  GetHostByName($_SERVER['SERVER_NAME']);
	//客户IP
	$systemInfo['cip'] = GCIP();
	//域名
	$systemInfo['hostname'] = $_SERVER["HTTP_HOST"];
	//服务时间
	$systemInfo['time'] = date("Y-m-d l H:i:s");
	return $systemInfo;
}

/**
 * 不区分大小写的in_array实现
 * @param  [type] $value [description]
 * @param  [type] $array [description]
 * @return [type]        [description]
 */
function in_array_case($value,$array){
	$max = getArrayMax($array);
	switch ($max) {
		case 1:
			return in_array(strtolower($value), array_map('strtolower',$array));
		case 2:
			return array_key_exists(strtolower($value), array_change_key_case($array, CASE_LOWER));
		default:
			Debug::add('<font color="red">目前只能查找一维数组与二维数组!');
			break;
	}
}

/**
 * 判断几维数组
 * @param  [type] $arr [description]
 * @return [type]      [description]
 */
function getArrayMax($arr){
	if(!is_array($arr)){
		return 0;
	}else{
		$dimension = 0;
		foreach($arr as $item1){
			$t1 = getArrayMax($item1);
			if($t1 > $dimension){
				$dimension = $t1;
			}
		}
		return $dimension+1;
	}
}

/**
* 返回一个关联数组
* @return [type] [description]
*/
function get_called_method() {
	$backtrace = debug_backtrace();
	array_shift($backtrace);
	return $backtrace[1]['function'];
}

/**
 * 压缩Html代码
 * @param  [type] $string [Html字符串]
 * @return [type]         [description]
 */
function cpressHtml($string){
	$string=str_replace("\r\n",'',$string);//清除换行符
	$string=str_replace("\n",'',$string);//清除换行符
	$string=str_replace("\t",'',$string);//清除制表符
	$pattern=array(
		"/> *([^ ]*) *</",//去掉注释标记
		"/[\s]+/",
		"/<!--[^!]*-->/",
		"/\" /",
		"/ \"/",
		"'/\*[^*]*\*/'",
		);
	$replace=array (
		">\\1<",
		" ",
		"",
		"\"",
		"\"",
		"",
		);
	return preg_replace($pattern, $replace, $string);
}

/**
 * 引入文件
 * @param  [type] $file [description]
 * @return [type]       [description]
 */
function loadfile($file = null){
	if (is_null($file)) return false;
	if (file_exists($file)) {
		return include $file;
	}
	return false;
}

/**
 * 以 unserialize 读取文件
 * @param  [type] $file [description]
 * @return [type]       [description]
 */
function unfile($file = null){
	if (is_null($file)) return false;
	return unserialize(file_get_contents($file));
}

/**
 * 以 serialize 写入文件
 * @param  [type] $dir  [description]
 * @param  [type] $file [description]
 * @return [type]       [description]
 */
function serfile($dir = null, $file = null){
	if (is_null($file)) return;
	if (file_put_contents($dir, serialize($file))) {
		return true;
	}
}

/**
 * 以 var_export 写入文件
 * @param  [type] $dir  [description]
 * @param  [type] $data [description]
 * @return [type]       [description]
 */
function varfile($dir, $data){
	if (is_null($dir) || is_null($data)) return false;
	if (file_put_contents($dir, "<?php\nreturn ".var_export($data, true).";\n?>")) {
		return true;
	}
	return false;
}


